package javacommon.base;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author badqiu
 */
@Transactional
@SuppressWarnings({ "rawtypes", "unchecked" })
public abstract class BaseManager<E extends BaseEntity, PK extends Serializable> {

	protected Log log = LogFactory.getLog(getClass());

	protected abstract EntityDao getEntityDao();

	@Transactional(readOnly = true)
	public E getById(PK id) throws DataAccessException {
		return (E) getEntityDao().getById(id);
	}

	@Transactional(readOnly = true)
	public List<E> findAll() throws DataAccessException {
		return getEntityDao().findAll();
	}

	/** 根据id检查是否插入或是更新数据 */
	public void saveOrUpdate(E entity) throws DataAccessException {

		try {
			getEntityDao().saveOrUpdate(entity);
		} catch (DataAccessException e) {
			throw e;
		}
	}

	/** 插入数据 */
	public void save(E entity) throws DataAccessException {
		getEntityDao().save(entity);

	}

	public void removeById(PK id) throws DataAccessException {

		getEntityDao().deleteById(id);
	}

	public void update(E entity) throws DataAccessException {
		try {
			getEntityDao().update(entity);
		} catch (DataAccessException e) {
			throw e;
		}

	}

	/**
	 * 判断对象某些属性的值在数据库中是否唯一，如果是唯一则返回true，如果不是唯一，则返回false
	 */
	@Transactional(readOnly = true)
	public boolean isUnique(E entity, String uniquePropertyNames) throws DataAccessException {
		return getEntityDao().isUnique(entity, uniquePropertyNames);
	}

	/**
	 * 安全验证
	 * 
	 * @param dataId
	 *            数据id
	 * @param userId
	 *            用户id
	 * @param type
	 *            验证类型
	 * @return
	 */
	public boolean safetyChecking(long dataId, Set<Long> ids) {
		return false;
	};

}
